package com.geek.water.controller;

import com.aliyuncs.exceptions.ClientException;

import com.geek.water.constant.CodeConstant;
import com.geek.water.constant.RedisMessageConstant;
import com.geek.water.result.Result;

import com.geek.water.utils.AliyunSMSUtils;
import com.geek.water.utils.ValidateCodeUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.geek.water.constant.MessageConstant;
import java.util.concurrent.TimeUnit;
import com.geek.water.service.SmsService;
import lombok.RequiredArgsConstructor;

/**
 * @author chenmin
 * @desc TODO
 * @date 2025/8/7
 */
@RestController
@RequestMapping("/app/sms")
@RequiredArgsConstructor
public class SmsController {

    private final SmsService smsService;
    private final StringRedisTemplate redisTemplate;

    //@Resource  可以指定name名称匹配，也可以指定type类型匹配
    /*@Resource(name = "stringRedisTemplate")
    private StringRedisTemplate redisTemplate;*/

    @ApiOperation("登录时发送短信验证码")
    @PostMapping("sendMsgByLogin")
    public Result sendMsgByLogin(String phone) throws ClientException {
        //1.先查询此手机号是否是一分钟内重复发送验证码，若是直接返回
        if(redisTemplate.opsForValue().get(phone+ RedisMessageConstant.SENDTYPE_LOGIN) !=null){
            return new Result(CodeConstant.FAIL , MessageConstant.SEND_VALIDATE_CODE_HAS);
        }

        //2.生成四位短信验证码 ， 并且发送短信验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        boolean flag = smsService.sendMessage(AliyunSMSUtils.VALIDATE_CODE, phone, code);
        if(flag){
            //3.存储验证码至Redis，一分钟内有效  phone_001
            //  存储验证码至Redis，五分钟内有效  phone_001_code
            redisTemplate.opsForValue().set(phone+ RedisMessageConstant.SENDTYPE_LOGIN , code , 1 , TimeUnit.MINUTES);
            redisTemplate.opsForValue().set(phone+ RedisMessageConstant.SENDTYPE_LOGIN+"_"+code , code , 5 , TimeUnit.MINUTES);

            return new Result(CodeConstant.SUCCESS , MessageConstant.SEND_VALIDATE_CODE_SUCCESS);
        }
        return new Result(CodeConstant.FAIL , MessageConstant.SEND_VALIDATE_CODE_FAIL);
    }

}
